﻿using LD.Model;
using LD.Tool;
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;

namespace LD.Host.项目
{
    public partial class FrmKazamPress : BaseFrm
    {
        private string barId = Guid.NewGuid().ToString("N");
        private string slotId = Guid.NewGuid().ToString("N");
        public FrmKazamPress()
        {
            InitializeComponent();
            this.FormClosing += FrmKazamPress_FormClosing;
            this.Shown += FrmKazamPress_Shown;
        }

        private void FrmKazamPress_Shown(object sender, EventArgs e)
        {
            Init();
        }

        private void FrmKazamPress_FormClosing(object sender, FormClosingEventArgs e)
        {
            PubSub.Hub.Default.Unsubscribe<BarcodeHandle>(barId);
            PubSub.Hub.Default.Unsubscribe<KazamHandle>(slotId);
        }

        private void Init()
        {
            PubSub.Hub.Default.Subscribe<BarcodeHandle>(barId, Slot_Barcode);
            PubSub.Hub.Default.Subscribe<KazamHandle>(slotId, Kazam_Slot);
            KazamService.Ins.Start();

            Start();
        }
        public void Slot_Barcode(BarcodeHandle bar)
        {
            this.BeginInvoke(new Action(() =>
            {
                var ctl = getSlot(bar.Slot);
                if (ctl == null)
                    return;

                ctl.Barcode = bar.Barcode;
                ctl.StateMsg = string.IsNullOrEmpty(bar.Barcode) ? "扫码失败" : "扫码成功";
                ctl.State = string.IsNullOrEmpty(bar.Barcode) ? KazamState.Error : KazamState.Start;
            }));
        }
        public void Kazam_Slot(KazamHandle kaz)
        {
            this.Invoke(new Action(() =>
            {
                var ctl = getSlot(kaz.Slot);
                if (ctl == null)
                    return;

                ctl.StateMsg = kaz.message;
                ctl.State = kaz.kazamState;
            }));
        }
        private CtlSLOT getSlot(string slot)
        {
            if (slot == null)
                return null;
            var ctl = this.Controls.Find(slot, false).FirstOrDefault();
            if (ctl == null)
                return null;
            else
                return (CtlSLOT)ctl;
        }
        private void Start()
        {
            //启动扫码枪

        }
    }
}
